module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", _theme = "light";
    function setTheme(theme) {
        if (1 == 1) return;
        let classList = document.querySelector("html")?.classList;
        if (!classList) return;
        classList.remove("dark" == theme ? "__fb-light-mode" : "__fb-dark-mode");
        classList.add("dark" == theme ? "__fb-dark-mode" : "__fb-light-mode");
        let els = document.querySelectorAll("dark" == theme ? '.__fb-light-mode' : '.__fb-dark-mode');
        els?.forEach((el) => {
            classList = el?.classList;
            if (classList) {
                classList.remove("dark" == theme ? "__fb-light-mode" : "__fb-dark-mode");
                classList.add("dark" == theme ? "__fb-dark-mode" : "__fb-light-mode");
            }
        });
    }
    window.addEventListener('load', () => {
        setTheme(_theme);
    });
    function isGroup() {
        let el = document.querySelectorAll(".x9f619.x1n2onr6.x1ja2u2z.x78zum5.x1r8uery.x1iyjqo2.xs83m0k.xeuugli.x1qughib.x6s0dn4.xozqiw3.x1q0g3np.xykv574.xbmpl8g.x4cne27.xifccgj .x1lliihq.x193iq5w.x1us19tq.xl1xv1r");
        return el?.length > 1;
    }
    async function getChatId(times = 0) {
        let url = window.location.href;
        let id = '';
        if (url.startsWith("https://www.messenger.com/new")) {
            id = "new";
        } else {
            const regex = /\/t\/(\d+)\/?/;
            const match = regex.exec(url);
            try {
                if (match) id = match[1];
            } catch (error) {
                console.log('获取对话id失败', error)
            }
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    return {
        config: {
            friendList: 'div[role="navigation"][aria-label]',
            chat: 'div[role="main"][aria-label]',
            input: 'div[role="main"][aria-label] div[aria-label][role="group"] div[role="textbox"][data-lexical-editor="true"]',
            msgBox: 'div.x78zum5.xdt5ytf.x1iyjqo2.x5yr21d>div[role="grid"]',
            inMsg: 'div[data-scope="messages_table"][role="gridcell"] div.html-div.x5od304.x11ucwad.xgtuqic>span[dir="auto"]:not(.trans-inited)',
            outMsg: 'div[data-scope="messages_table"][role="gridcell"] div.html-div.xp5s12f.x155c047>span[dir="auto"]:not(.trans-inited)',
            sendBtn: 'div[role="main"][aria-label] div[aria-label][role="group"]>span>div.x1c4vz4f.x2lah0s[aria-label][role="button"]',
            setting: 'div.x78zum5.x1iyjqo2.x6q2ic0>div.x16sw7j7.x107yiy2.xv8uw2v.x1tfwpuw.x2g32xy.x9f619.xlai7qp.x1iyjqo2.xeuugli>div.x78zum5.x13a6bvl>div.x78zum5.x1iyjqo2.xq8finb.x16n37ib.x1xmf6yo.x1e56ztr.xeuugli.x1n2onr6',
            tips: {
                in: 'div.html-div.x1cy8zhl.xdt5ytf.x1iyjqo2',
                out: 'div[role="main"][aria-label] div[aria-label][role="group"]'
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: 'div[role="main"][aria-label] h2.html-h2[dir="auto"]',
                left: ""
            },
            placeholder: {
                selector: 'div.x78zum5.x13a6bvl div[aria-hidden="true"]>div',
                delay: 200,
                update: true
            },
            extra: {//其他会触发对话框变动的情况处理
                selector: 'ul[role="listbox"],span[role="gridcell"]>div>div[role="button"]',
                level: 20,
                delay: 600,
            },
            initChat: true,
            autoCount: 20
        },
        setTheme({ theme }) {
            _theme = theme;
            setTheme(theme);
        },
        getUnread() {
            const els = document.querySelectorAll('div.x9f619.xdl72j9.x2lwn1j.x1n2onr6.x1ja2u2z.x6s0dn4.x78zum5.x1q0g3np.xs83m0k.xl56j7k.x15kz4h8>div.x6s0dn4.x78zum5.xozqiw3 span.x6s0dn4.xzolkzo.x12go9s9.x1rnf11y.xprq8jg.x9f619.x3nfvp2.xl56j7k[data-visualcompletion="ignore"]');
            return els?.length;
        },
        getChatInfo() {
            return new Promise((resolve) => {
                EdtApi.sleep(300).then(async () => {
                    chatId = await getChatId();
                    resolve({ id: chatId, isGroup: isGroup() })
                }).catch(() => { });
            });
        },
        getChatTitle(chatEl = document) {
            let titleEl = chatEl.querySelector('h2.html-h2[dir="auto"] span.html-span,h1.html-h1[dir="auto"] span.html-span');
            if (!titleEl) return "";
            if (!titleEl.querySelector('img')) return titleEl.textContent || '';
            let title = "", img;
            titleEl.childNodes?.forEach(child => {
                if (child.nodeName == '#text') {
                    title += child.textContent || "";
                } else {
                    img = child.querySelector("img");
                    title += img?.alt || "";
                }
            });
            return title;
        },
        getText(msgBox) {
            try {
                let text = '', img;
                if (msgBox.querySelector('img')) {
                    msgBox.childNodes?.forEach(item => {
                        if ("SPAN" == item.tagName) {
                            img = item.querySelector('img');
                            if (img) text += img.getAttribute("alt");
                        } else {
                            text += item.textContent;
                        }
                    });
                } else {
                    text = msgBox.textContent;
                }
                return text ? text.trimEnd() : '';
            } catch (error) {
                console.error(error);
            }
            return "";
        },
        getIptMsg(inputEl) {
            if (!inputEl) return '';
            try {
                let texts = [], items = inputEl.querySelectorAll('p.xat24cr.xdj266r.xdpxx8g');
                let len = items.length;
                items?.forEach((item, index) => {
                    item.childNodes?.forEach(child => {
                        if ("emoji" == child.getAttribute("data-testid")) {
                            texts.push(child.textContent);
                        } else if ("BR" == child.tagName) {
                            texts.push("\n");
                        } else {
                            texts.push(child.textContent);
                        }
                    });
                    if (index < len - 1) texts.push("\n");
                });
                if (0 == texts.length) return "";
                return texts.join("");
            } catch (error) {
                console.error(error);
            }
            return "";
        },
        beforeSend({ chatEl }) {//处理语音发送
            let obj = {
                result: true,
                fileInput: null
            };
            return new Promise((resolve) => {
                let audioEl = chatEl.querySelector(`${this.config.tips.out} div.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj`);
                if (!audioEl) return resolve(obj);
                let sendBtn = chatEl.querySelector(this.config.sendBtn);
                sendBtn?.click();
                obj.result = false;
                resolve(obj);
            });
        },
        getUserInfo() {
            try {
                let avatarEl = document.querySelector('div[aria-label][role="button"] svg[role="img"]>g>image');
                let avatar = avatarEl?.getAttribute("xlink:href") || "";
                let userNameEl = document.querySelector('div.x9f619.x1n2onr6.x1ja2u2z.x78zum5.xdt5ytf.x2lah0s.x193iq5w.xeuugli.xexx8yu.x4uap5.x18d9i69.xkhd6sd>div.x1rg5ohu.x1n2onr6.x3ajldb.x1ja2u2z>svg.x3ajldb[aria-label]');
                let userName = userNameEl?.getAttribute("aria-label") || "";
                let account = " ";
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                };
            } catch (error) {
                return null;
            }
        }
    }
};